package xkp.lesson2;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    //同一主机上两个进程的网络端口号不能重复
    //端口号范围0---65535  端口号本质上是一个short值
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8888);
        Socket socket = serverSocket.accept();
        //1、首先接收文件名称
        DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
        String fileName = dataInputStream.readUTF();
        //2、读取文件数据，存入新文件
        String newFilePath = "D:\\network\\"+fileName;
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
                new FileOutputStream(newFilePath));
        byte[] buf = new byte[1024];
        int length = dataInputStream.read(buf);
        while(length != -1){
            bufferedOutputStream.write(buf,0,length);
            length = dataInputStream.read(buf);
        }
        dataInputStream.close();
        bufferedOutputStream.flush();
        bufferedOutputStream.close();
        socket.close();
        serverSocket.close();
    }
}
